package top.zsyle.system.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import top.zsyle.system.domain.Menu;
import top.zsyle.system.mapper.MenuMapper;
import top.zsyle.system.service.IMenuService;
import top.zsyle.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zsy
 * @since 2022-11-29
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;


    /**
     * 无限级树
     * @return
     */
    @Override
    public List<Menu> tree() {
        List<Menu> allMenus = menuMapper.findAll();
        ArrayList<Menu> menuTree = new ArrayList<>();
        Map<Long, Menu> menuMap = allMenus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        for (Menu menu : allMenus) {
            if (null == menu.getParentId()){
                //顶级菜单
                menuTree.add(menu);
            }else {
                Menu parent = menuMap.get(menu.getParentId());
                if (parent != null){
                    parent.getChildren().add(menu);
                }
            }
        }
        return menuTree;
    }
}
